package com.yuanfeng.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.business.dto.*;
import com.yuanfeng.business.entity.ShopBaseEntity;
import com.yuanfeng.business.entity.ShopFxGoodsInfoEntity;
import com.yuanfeng.business.entity.ShopTransportRuleEntity;
import com.yuanfeng.business.entity.ShopTransportTemplateEntity;
import com.yuanfeng.business.feign.ActivityServiceClient;
import com.yuanfeng.business.feign.GoodsServiceClient;
import com.yuanfeng.business.mapper.*;
import com.yuanfeng.business.service.ShopTransportTemplateService;
import com.yuanfeng.business.vo.DealerSetVO;
import com.yuanfeng.business.vo.GdbMerchantShopBaseVO;
import com.yuanfeng.business.vo.GdbMerchantTransportTemplateVO;
import com.yuanfeng.business.vo.TransportTemplateListVO;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.goods.ActivityGoodsDetailDTO;
import com.yuanfeng.commoms.dto.goods.ManjianzengzheGoodsRuleQueryDTO;
import com.yuanfeng.commoms.enums.DealerSetKey;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.ListSort;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.activity.AppDiscountGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.activity.AppPintuanGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.activity.AppSeckillGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.activity.ManjianzengzheGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.goods.ReceiveGoodsDetailsVO;
import com.yuanfeng.commoms.vo.order.*;
import com.yuanfeng.commoms.vo.shop.TransportTemplateVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;

/**
 * @ClassName ShopTransportTemplateServiceImpl
 * @Description 运费模板表
 * @Author cyp
 * @Date 2023-05-29 13:55:18
 * @Version 1.0
 **/
@Service
public class ShopTransportTemplateServiceImpl extends ServiceImpl<ShopTransportTemplateMapper, ShopTransportTemplateEntity>
        implements ShopTransportTemplateService {
    @Autowired
    private ShopBaseMapper shopBaseMapper;
    @Autowired
    private ShopFxGoodsInfoMapper shopFxGoodsInfoMapper;
    @Autowired
    private ShopTransportAreaMapper shopTransportAreaMapper;
    @Autowired
    private GoodsServiceClient goodsServiceClient;
    @Autowired
    private ActivityServiceClient activityServiceClient;
    @Autowired
    private ShopTransportTemplateMapper shopTransportTemplateMapper;
    @Autowired
    private ShopTransportRuleMapper shopTransportRuleMapper;

    @Override
    public ResponseResult queryShipping(String message) {
        ResponseResult resp = new ResponseResult();
        CommonParameterVO commonParam = JsonUtils.string2Obj(message, CommonParameterVO.class);
        // 结果集
        List<WapShopShippingQueryResultVO> otherResults = Lists.newArrayList();

        List<StoreInformationVO> storeInformationList = commonParam.getStoreInformationList();
        Integer areaId = commonParam.getOrderReceiverAreaId();
        Integer orderReceiverCityId = commonParam.getOrderReceiverCityId();
        Integer orderReceiverProvinceId = commonParam.getOrderReceiverProvinceId();

        // 查询经销商和供应商佣金比例
        DealerSetVO dealerCommission =  this.baseMapper.queryDealerSet(DealerSetKey.dealer_commission.name());
        DealerSetVO supplyCommission =  this.baseMapper.queryDealerSet(DealerSetKey.supply_commission.name());
        Map<Integer,Integer> goodsFlagMap = new HashMap<>();

        for (StoreInformationVO storeInformation : storeInformationList) {
            // 获取购物车的店铺id和商品信息
            List<GoodsInformationVO> goodsList = storeInformation.getGoodsBaseList();
            List<Integer> goodsIdList = Lists.newArrayList();

            for (GoodsInformationVO goodsInformation : goodsList) {
                goodsIdList.add(goodsInformation.getGoodsId());
                goodsFlagMap.put(goodsInformation.getGoodsId(),goodsInformation.getType());
            }
            Integer shopId = storeInformation.getShopId();
            // 店铺运费
            BigDecimal shopShippingFee = new BigDecimal(0);
            // 根据区域模板id分组后的商品列表
            List<WapShopShippingResultVO> transportGroupGoodList = Lists.newArrayList();
            // 查询店铺信息
            WapShopShippingQueryResultVO shopBase = shopBaseMapper.selectByShopId(shopId);
            //判读是否是 积分商品
            if(null != commonParam.getIntegralGoods() && commonParam.getIntegralGoods() ==0){
                shopBase = new WapShopShippingQueryResultVO();
                shopBase.setShopId(0);
                shopBase.setShopName("平台店铺");
                shopBase.setShopFreeShipping(BigInteger.valueOf(0));
                shopBase.setShopInvoices(0);
                shopBase.setDistrictId(0);
                shopBase.setTreasureGradeId(0);
                shopBase.setShopSelfSupport(false);

            }
            if (null == shopBase) {
                return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED.getMsg());
            }

            ////////////////////////////////////////////////////////////////////////////////////////
            // 判断是否为小宝商品
            if (goodsList.size() == 1) {
                List<WapShippingQueryResultVO> goodsBases = this.baseMapper.selectShipping2(goodsIdList);
                WapShippingQueryResultVO babyGoodsBase = goodsBases.get(0);
                if (goodsBases.size() == 1 && babyGoodsBase.getCommonType().equals(2)) {
                    babyGoodsBase.setGoodsShippingFee(new BigDecimal(0));
                    WapShopShippingResultVO  babyShopShiping = new WapShopShippingResultVO();
                    babyShopShiping.setGoodsBaseList(goodsBases);
                    babyShopShiping.setGrossFreight(new BigDecimal(0));
                    transportGroupGoodList.add(babyShopShiping);
                    shopBase.setGoodsBaseList(transportGroupGoodList);
                    otherResults.add(shopBase);
                    return ResponseResult.success(1, JsonUtils.toString(otherResults), null);
                }
            }
            ///////////////////////////////////////////////

            // 店铺免额度
            BigInteger shopFreeShipping = shopBase.getShopFreeShipping();
            shopBase.setBuyerMessage(storeInformation.getBuyerMessage());

            // 商品价格,与免额度比较
            BigDecimal goodsPrice = new BigDecimal(0);

            // 获取商品详情并根据运费模板id分组
            List<WapShippingQueryResultVO> goodsBases = this.baseMapper.selectShipping2(goodsIdList);

            Map<Integer, List<WapShippingQueryResultVO>> transportAreaIdGroup = ListSort.byTransportAreaIdGroup(goodsBases);

            for (Map.Entry<Integer, List<WapShippingQueryResultVO>> integerListEntry : transportAreaIdGroup.entrySet()) {
                // 根据模板划分
                WapShopShippingResultVO shippingResult = new WapShopShippingResultVO();
                // 同运费模板运费
                BigDecimal grossFreight = new BigDecimal(0);
                // 同运费模板的数量
                Integer grossNum = 0;
                // 同运费模板的重量
                BigDecimal grossCubage = new BigDecimal(0);

                Integer transportTemplateId = integerListEntry.getKey();
                List<WapShippingQueryResultVO> goodsBaseList2 = integerListEntry.getValue();

                WapShippingTransportResultVO shippingTransport = this.baseMapper.selectShippingByTemple(transportTemplateId);
                if (null == shippingTransport) {
                    shippingTransport = this.baseMapper.selectShippingByTemple(1);
                }

                for (WapShippingQueryResultVO wapShippingQueryResult : goodsBaseList2) {
                    //判断商品是否供应商代发货商品
                    if (null != wapShippingQueryResult.getDealerGoodsFlag() && wapShippingQueryResult.getDealerGoodsFlag() == 1) {
                        // 查询商品供应商
                        GdbMerchantShopBaseVO supplyShopBase = shopBaseMapper.selectSupplierShopByPrimaryKey(wapShippingQueryResult.getSupplyShopId());
                        wapShippingQueryResult.setSupplyShopName(supplyShopBase.getShopName());
                        Map<String, Object> supplyGoodsBase = this.baseMapper.queryByGoodsId(wapShippingQueryResult.getSupplierGoodsId());

                        wapShippingQueryResult.setDealerGoodsPrice(new BigDecimal(supplyGoodsBase.get("goods_price").toString()));
                        // 待发货商品佣金比例
                        wapShippingQueryResult.setDealerCommission(null == dealerCommission ? "0" : dealerCommission.getValue1());
                        wapShippingQueryResult.setSupplyCommission(null == supplyCommission ? "0" : supplyCommission.getValue1());
                    } else {
                        wapShippingQueryResult.setSupplyShopId(shopId);
                        wapShippingQueryResult.setSupplyShopName(shopBase.getShopName());
                        wapShippingQueryResult.setDealerGoodsPrice(BigDecimal.ZERO);
                    }
                    //根据commonid 查询参与分销商品的规格
                    Integer goodsId = this.baseMapper.queryFxGuigeGoodsId(wapShippingQueryResult.getCommonId());
                    // 查询分销信息
                    ShopFxGoodsInfoEntity fxGoodsInfo = shopFxGoodsInfoMapper.selectOne(new LambdaQueryWrapper<ShopFxGoodsInfoEntity>()
                            .eq(ShopFxGoodsInfoEntity::getGoodsId, goodsId));
                    if (null != fxGoodsInfo) {
                        wapShippingQueryResult.setFxRate(fxGoodsInfo.getFxRate());
                        wapShippingQueryResult.setTgRate(fxGoodsInfo.getTgRate());
                        wapShippingQueryResult.setFxGoods(1);
                    } else {
                        wapShippingQueryResult.setFxRate("0");
                        wapShippingQueryResult.setTgRate("0");
                        wapShippingQueryResult.setFxGoods(0);
                    }

                    if (null != wapShippingQueryResult.getGoodsType()) {
                        if (wapShippingQueryResult.getGoodsType() == 2 && (commonParam.getOrderSource() != null && commonParam.getOrderSource() != 1)) {
                            wapShippingQueryResult.setGoodsPrice(wapShippingQueryResult.getGuidePrice());
                        }
                    }
                    for (GoodsInformationVO goodsBase : goodsList) {

                        // ====================售卖区域 开始======================//
                        String shopAreaIds = shopTransportAreaMapper
                                .selectByTransportAreaIds(wapShippingQueryResult.getTransportAreaId());
                        Integer virtualGoods = 0;
                        virtualGoods = this.baseMapper.queryVirtualGoods(goodsBase.getGoodsId());
                        if (null == virtualGoods) {
                            virtualGoods = 0;
                        }
                        // 全国有货
                        if (null != shopAreaIds && !shopAreaIds.isEmpty() && !"0".equals(shopAreaIds) && virtualGoods == 1) {
                            // 判断传入区域是否有货
                            List<String> areaIdsList = Arrays.asList(shopAreaIds.split(","));
                            if (!areaIdsList.contains(JsonUtils.toString(orderReceiverCityId))) {
                                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.PRODUCTS_OUT_OF_STOCK_IN_THIS_SALES_AREA.getMsg(), wapShippingQueryResult.getGoodsName());
                            }

                        }
                        // ====================售卖区域 结束======================//

                        // ====================活动 开始======================//
                        ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(wapShippingQueryResult.getGoodsId(),
                                wapShippingQueryResult.getGoodsMaxSale(), wapShippingQueryResult.getCommonId(),
                                wapShippingQueryResult.getCommonIsXian());
                        boolean actFlag = true;
                        if (null != goodsFlagMap.get(wapShippingQueryResult.getGoodsId())
                                && 1 == goodsFlagMap.get(wapShippingQueryResult.getGoodsId())
                                && null != wapShippingQueryResult.getCommonIsXian()
                                && 3 == wapShippingQueryResult.getCommonIsXian()
                        ) {
                            actFlag = false;
                        }


                        if (null != activityGoodsDetail && actFlag) {
                            wapShippingQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                            wapShippingQueryResult.setActivityGoodsDetail(activityGoodsDetail);
                            wapShippingQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                        } else {
                            wapShippingQueryResult.setActivityStatus(0);
                            wapShippingQueryResult.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                            wapShippingQueryResult.setCommonIsXian(0);
                        }
                        // ====================活动 结束======================//

                        if (wapShippingQueryResult.getGoodsMaxSale().equals(0)) {
                            wapShippingQueryResult.setGoodsMaxSale(wapShippingQueryResult.getGoodsStock());
                        }

                        if (goodsBase.getGoodsId().equals(wapShippingQueryResult.getGoodsId())) {

                            // 拼团类型和团长id
                            if (wapShippingQueryResult.getCommonIsXian().equals(4) &&
                                    (commonParam.getPlatForm() == null || commonParam.getPlatForm() != 1)) {
                                ActivityGoodsDetailDTO activityGoodsDetail2 = wapShippingQueryResult
                                        .getActivityGoodsDetail();

                                if (null != goodsBase.getType()) {
                                    activityGoodsDetail2.setType(goodsBase.getType());
                                    activityGoodsDetail2.setMarkId(goodsBase.getMarkId());
                                } else {
                                    wapShippingQueryResult.setActivityStatus(0);
                                    wapShippingQueryResult.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                                    wapShippingQueryResult.setCommonIsXian(0);
                                }
                            }

                            wapShippingQueryResult.setGoodsSpec(wapShippingQueryResult.getGoodsSpec());

//                            String commonSpecName = goodsSpecMapper
//                                    .selectBySpecId(Integer.parseInt(wapShippingQueryResult.getCommonSpecName()));
//                            wapShippingQueryResult.setCommonSpecName(commonSpecName);

                            wapShippingQueryResult.setGoodsNum(goodsBase.getGoodsNum());
                            grossNum = grossNum + goodsBase.getGoodsNum();
                            grossCubage = grossCubage.add(wapShippingQueryResult.getGoodsCubage()
                                    .multiply(new BigDecimal(goodsBase.getGoodsNum())));
                            goodsPrice = goodsPrice.add(wapShippingQueryResult.getGoodsPrice()
                                    .multiply(new BigDecimal(goodsBase.getGoodsNum())));

                        }
                    }
                }

                // 查询运费规则
                if (transportTemplateId.intValue() == 0) {
                    grossFreight = new BigDecimal(0);
                    for (WapShippingQueryResultVO goodsBase : goodsBaseList2) {
                        goodsBase.setGoodsShippingFee(grossFreight);
                    }
                } else {
                    if (null != shippingTransport) {
                        grossFreight = getShipping(grossFreight, areaId, orderReceiverCityId, orderReceiverProvinceId,
                                grossNum, grossCubage, shippingTransport, goodsBaseList2, goodsList);
                    }
                }

                shopShippingFee = shopShippingFee.add(grossFreight);
                shippingResult.setGrossFreight(grossFreight);
                shippingResult.setGoodsBaseList(goodsBaseList2);
                transportGroupGoodList.add(shippingResult);
            }

            if (null != shopFreeShipping && shopFreeShipping.compareTo(BigInteger.ZERO) > 0) {
                if (goodsPrice.compareTo(new BigDecimal(shopFreeShipping)) == 1
                        || goodsPrice.compareTo(new BigDecimal(shopFreeShipping)) == 0) {
                    shopBase.setShippingFee(new BigDecimal(0));
                    for (WapShopShippingResultVO wapShippingQueryResult2 : transportGroupGoodList) {
                        for (WapShippingQueryResultVO shippingQueryResult2 : wapShippingQueryResult2.getGoodsBaseList()) {
                            shippingQueryResult2.setGoodsShippingFee(new BigDecimal(0));
                        }
                    }

                } else {
                    shopBase.setShippingFee(shopShippingFee);
                }
            } else {
                shopBase.setShippingFee(shopShippingFee);
            }
            shopBase.setGoodsBaseList(transportGroupGoodList);
//            shopBase.setHotBindGoods(bindGoodsList);
            otherResults.add(shopBase);
        }
        if(resp.getCode() == 10013){
            return  ResponseResult.success(1, JsonUtils.toString(otherResults), resp.getMessage());
        }else{
            return  ResponseResult.success(JsonUtils.toString(otherResults));
        }
    }
    //运费计算
    private BigDecimal getShipping(BigDecimal shippingFee, Integer areaId, Integer orderReceiverCityId,
                                   Integer orderReceiverProvinceId, Integer num, ShippingInfoDTO goodsBase,
                                   ShopTransportTemplateEntity shippingTransport){
        if (shippingTransport.getIsFreePostage().equals(CommonType.shippingStart.CUSTOMIZATION_SHIPPING.getCode())) {
            // 自定义
            ShopTransportRuleEntity defaultTransportRule = null;
            // 判断是否在包邮区域内
            String freePostageAreas = shippingTransport.getFreePostageAreas();
            if ("".equals(freePostageAreas) || null == freePostageAreas) {
                freePostageAreas = "0";
            }
            List<Integer> freeAreaIds = JsonUtils.StringToList2(freePostageAreas);
            if (null == shippingTransport.getRuleType()) {
                shippingTransport.setRuleType(CommonType.shippingStart.WEIGHT.getCode());
            }

            // 按件数包邮
            if (shippingTransport.getRuleType().equals(CommonType.shippingStart.ITEM.getCode())) {

                if (freeAreaIds.contains(areaId)) {
                    // 包邮
                    if (shippingTransport.getFreePostageCond() <= num) {
                        goodsBase.setGoodsShippingFee(shippingFee);
                    } else {
                        // 不满足包邮
                        shippingFee = shippingFee.add(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                : new BigDecimal(shippingTransport.getShippingPrice()));
                        goodsBase.setGoodsShippingFee(shippingFee);
                    }
                } else if (freeAreaIds.contains(orderReceiverCityId)) {
                    // 包邮
                    if (shippingTransport.getFreePostageCond() <= num) {
                        goodsBase.setGoodsShippingFee(shippingFee);
                    } else {
                        // 不满足包邮
                        shippingFee = shippingFee.add(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                : new BigDecimal(shippingTransport.getShippingPrice()));
                        goodsBase.setGoodsShippingFee(shippingFee);
                    }
                } else if (freeAreaIds.contains(orderReceiverProvinceId)) {
                    // 包邮
                    if (shippingTransport.getFreePostageCond() <= num) {
                        goodsBase.setGoodsShippingFee(shippingFee);
                    } else {
                        // 不满足包邮
                        shippingFee = shippingFee.add(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                : new BigDecimal(shippingTransport.getShippingPrice()));
                        goodsBase.setGoodsShippingFee(shippingFee);
                    }
                } else {
                    // 不包邮
                    Boolean flag = true;
                    List<ShopTransportRuleEntity> transportRules = shopTransportRuleMapper.selectList(new LambdaQueryWrapper<ShopTransportRuleEntity>()
                            .eq(ShopTransportRuleEntity::getTransportTemplateId,goodsBase.getTransportTemplate())
                            .orderByDesc(ShopTransportRuleEntity::getDefaultType));
                    for (ShopTransportRuleEntity transportRule : transportRules) {

                        if (transportRule.getDefaultType().equals(CommonType.shippingStart.DEFAULT_RULES.getCode())) {
                            defaultTransportRule = transportRule;
                        }

                        List<Integer> areaIds = JsonUtils.StringToList2(transportRule.getAreaIds());
                        if (areaIds.contains(areaId)) {
                            flag = false;
                            // 首重数量
                            BigDecimal defaultNum = transportRule.getDefaultNum();
                            BigDecimal defaultPrice = new BigDecimal(transportRule.getDefaultPrice());
                            BigDecimal addNum = transportRule.getAddNum();
                            BigDecimal addPrice = new BigDecimal(transportRule.getAddPrice());
                            // 判断是否在首件内
                            if (defaultNum.compareTo(new BigDecimal(num)) > 0
                                    || defaultNum.compareTo(new BigDecimal(num)) == 0) {
                                shippingFee = shippingFee.add(defaultPrice);
                                goodsBase.setGoodsShippingFee(defaultPrice);
                            } else {
                                // 超过首件

                                BigDecimal price = (new BigDecimal(num).subtract(defaultNum).divide(addNum, 2,
                                        RoundingMode.DOWN)).multiply(addPrice)
                                        .add((new BigDecimal(num)).multiply(defaultPrice));
                                shippingFee = shippingFee.add(price);
                                goodsBase.setGoodsShippingFee(price);
                            }
                            break;
                        } else if (areaIds.contains(orderReceiverCityId)) {
                            flag = false;
                            // 首重数量
                            BigDecimal defaultNum = transportRule.getDefaultNum();
                            BigDecimal defaultPrice = new BigDecimal(transportRule.getDefaultPrice());
                            BigDecimal addNum = transportRule.getAddNum();
                            BigDecimal addPrice =  new BigDecimal(transportRule.getAddPrice());
                            // 判断是否在首件内
                            if (defaultNum.compareTo(new BigDecimal(num)) > 0
                                    || defaultNum.compareTo(new BigDecimal(num)) == 0) {
                                shippingFee = shippingFee.add(defaultPrice);
                                goodsBase.setGoodsShippingFee(defaultPrice);
                            } else {
                                // 超过首件
                                BigDecimal price = (new BigDecimal(num).subtract(defaultNum).divide(addNum, 2,
                                        BigDecimal.ROUND_DOWN)).multiply(addPrice)
                                        .add((new BigDecimal(num)).multiply(defaultPrice));
                                shippingFee = shippingFee.add(price);
                                goodsBase.setGoodsShippingFee(price);
                            }
                            break;
                        }
                    }
                    if (flag) {
                        if (defaultTransportRule != null) {
                            // 默认规则
                            BigDecimal defaultNum = defaultTransportRule.getDefaultNum();
                            BigDecimal defaultPrice = new BigDecimal(defaultTransportRule.getDefaultPrice());
                            BigDecimal addNum = defaultTransportRule.getAddNum();
                            BigDecimal addPrice = new BigDecimal(defaultTransportRule.getAddPrice());
                            // 判断是否在首件内

                            if (defaultNum.compareTo(new BigDecimal(num)) == 1
                                    || defaultNum.compareTo(new BigDecimal(num)) == 0) {
                                shippingFee = shippingFee.add(defaultPrice);
                                goodsBase.setGoodsShippingFee(defaultPrice);
                            } else {
                                // 超过首件
                                BigDecimal price = (new BigDecimal(num).subtract(defaultNum).divide(addNum, 2,
                                        BigDecimal.ROUND_DOWN)).multiply(addPrice).add(defaultPrice);
                                shippingFee = shippingFee.add(price);
                                goodsBase.setGoodsShippingFee(price);
                            }
                        } else {
                            goodsBase.setGoodsShippingFee(shippingFee);
                        }
                    }
                }
                // 按重量包邮
            } else {
                // 获取总重量
                BigDecimal allCubage = new BigDecimal(num)
                        .multiply(goodsBase.getGoodsCubage() == null ? new BigDecimal(0) : goodsBase.getGoodsCubage());

                if (freeAreaIds.contains(areaId)) {
                    // 包邮
                    if (shippingTransport.getFreePostageCond() <= allCubage.intValue()) {
                        shippingFee = shippingFee.add(new BigDecimal(0));
                        goodsBase.setGoodsShippingFee(new BigDecimal(0));
                    } else {
                        // 不满足包邮
                        shippingFee = shippingFee.add(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                :new BigDecimal(shippingTransport.getShippingPrice()));
                        goodsBase.setGoodsShippingFee(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                : new BigDecimal(shippingTransport.getShippingPrice()));
                    }
                } else if (freeAreaIds.contains(orderReceiverCityId)) {
                    // 包邮
                    if (shippingTransport.getFreePostageCond() <= allCubage.intValue()) {
                        shippingFee = shippingFee.add(new BigDecimal(0));
                        goodsBase.setGoodsShippingFee(new BigDecimal(0));
                    } else {
                        // 不满足包邮
                        shippingFee = shippingFee.add(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                : new BigDecimal(shippingTransport.getShippingPrice()));
                        goodsBase.setGoodsShippingFee(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                : new BigDecimal(shippingTransport.getShippingPrice()));
                    }
                } else if (freeAreaIds.contains(orderReceiverProvinceId)) {
                    // 包邮
                    if (shippingTransport.getFreePostageCond() <= allCubage.intValue()) {
                        shippingFee = shippingFee.add(new BigDecimal(0));
                        goodsBase.setGoodsShippingFee(new BigDecimal(0));
                    } else {
                        // 不满足包邮
                        shippingFee = shippingFee.add(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                : new BigDecimal(shippingTransport.getShippingPrice()));
                        goodsBase.setGoodsShippingFee(new BigDecimal(shippingTransport.getShippingPrice()) == null ? new BigDecimal(0)
                                : new BigDecimal(shippingTransport.getShippingPrice()));
                    }
                } else {
                    // 不包邮
                    Boolean flag = true;
                    List<ShopTransportRuleEntity> transportRules = shopTransportRuleMapper.selectList(new LambdaQueryWrapper<ShopTransportRuleEntity>()
                            .eq(ShopTransportRuleEntity::getTransportTemplateId,goodsBase.getTransportTemplate())
                            .orderByDesc(ShopTransportRuleEntity::getDefaultType));
                    for (ShopTransportRuleEntity transportRule : transportRules) {

                        if (transportRule.getDefaultType().equals(CommonType.shippingStart.DEFAULT_RULES.getCode())) {
                            defaultTransportRule = transportRule;
                        }

                        List<Integer> areaIds = JsonUtils.StringToList2(transportRule.getAreaIds());
                        if (areaIds.contains(areaId)) {
                            flag = false;
                            // 首重重量
                            BigDecimal defaultNum = transportRule.getDefaultNum();
                            BigDecimal defaultPrice = new BigDecimal(transportRule.getDefaultPrice());
                            BigDecimal addNum = transportRule.getAddNum();
                            BigDecimal addPrice = new BigDecimal(transportRule.getAddPrice());
                            // 判断是否在首件内
                            if (defaultNum.compareTo(allCubage) >= 0) {
                                shippingFee = shippingFee.add(defaultPrice);
                                goodsBase.setGoodsShippingFee(defaultPrice);
                            } else {
                                // 超过首件
                                BigDecimal price = allCubage.subtract(defaultNum)
                                        .divide(addNum, 2, BigDecimal.ROUND_DOWN).multiply(addPrice)
                                        .add(defaultNum.multiply(defaultPrice));
                                shippingFee = shippingFee.add(price);
                                goodsBase.setGoodsShippingFee(price);
                            }
                            break;
                        } else if (areaIds.contains(orderReceiverCityId)) {
                            flag = false;
                            // 首重重量
                            BigDecimal defaultNum = transportRule.getDefaultNum();
                            BigDecimal defaultPrice = new BigDecimal(transportRule.getDefaultPrice());
                            BigDecimal addNum = transportRule.getAddNum();
                            BigDecimal addPrice = new BigDecimal(transportRule.getAddPrice());
                            // 判断是否在首件内
                            if (defaultNum.compareTo(allCubage) >= 0) {
                                shippingFee = shippingFee.add(defaultPrice);
                                goodsBase.setGoodsShippingFee(defaultPrice);
                            } else {
                                // 超过首件
                                BigDecimal price = allCubage.subtract(defaultNum)
                                        .divide(addNum, 2, BigDecimal.ROUND_DOWN).multiply(addPrice)
                                        .add(defaultNum.multiply(defaultPrice));
                                shippingFee = shippingFee.add(price);
                                goodsBase.setGoodsShippingFee(price);
                            }
                            break;
                        }
                    }
                    if (flag) {

                        if (defaultTransportRule != null) {
                            // 默认规则
                            BigDecimal defaultNum = defaultTransportRule.getDefaultNum();
                            BigDecimal defaultPrice = new BigDecimal(defaultTransportRule.getDefaultPrice());
                            BigDecimal addNum = defaultTransportRule.getAddNum();
                            BigDecimal addPrice = new BigDecimal(defaultTransportRule.getAddPrice());
                            // 判断是否在首件内
                            if (defaultNum.compareTo(allCubage) >= 0) {
                                shippingFee = shippingFee.add(defaultPrice);
                                goodsBase.setGoodsShippingFee(defaultPrice);
                            } else {
                                // 超过首件
                                BigDecimal price = allCubage.subtract(defaultNum)
                                        .divide(addNum, 2, BigDecimal.ROUND_DOWN).multiply(addPrice).add(defaultPrice);
                                shippingFee = shippingFee.add(price);
                                goodsBase.setGoodsShippingFee(price);
                            }
                        } else {
                            goodsBase.setGoodsShippingFee(shippingFee);
                        }
                    }
                }
            }
        }

        return shippingFee;
    }

    private BigDecimal getShipping(BigDecimal shippingFee, Integer areaId, Integer orderReceiverCityId,
                                   Integer orderReceiverProvinceId, Integer num, BigDecimal grossCubage,
                                   WapShippingTransportResultVO shippingTransport, List<WapShippingQueryResultVO> goodsBaseList,List<GoodsInformationVO> goodsBases) {
        // 默认规则
        WapShippingTransportResultVO defaultTransportRule = null;
        if (shippingTransport.getIsFreePostage() == 2) {
            // 自定义
            // 包邮区域
            String freePostageAreas = shippingTransport.getFreePostageAreas();
            if (StringUtils.isEmpty(freePostageAreas)) {
                freePostageAreas = "0";
            }
            List<Integer> freeAreaIds = JsonUtils.StringToList2(freePostageAreas);

            // 按件数包邮
            if (shippingTransport.getRuleType() == 2) {

                if (freeAreaIds.contains(areaId)) {
                    for (WapShippingQueryResultVO goodsList : goodsBaseList) {
                        Integer buyNum = goodsList.getGoodsNum();
                        // 包邮
                        if (shippingTransport.getFreePostageCond().intValue() <= buyNum.intValue()) {
                            // 设置商品运费为0
                            setGoodsShippingZero(goodsBaseList);
                        } else {
                            shippingFee = shippingFee.add(shippingTransport.getShippingPrice() == null ? new BigDecimal(0)
                                    : shippingTransport.getShippingPrice());
                            // 不满足包邮
                            // 根据商品数量设置商品运费
                            goodsList.setTotalGoodsShippingFee(shippingTransport.getShippingPrice() == null ? new BigDecimal(0)
                                    : shippingTransport.getShippingPrice());
                            shippingFee = setNoFeeByNum(shippingFee, buyNum, shippingTransport, goodsBaseList);
                        }
                    }

                } else if (freeAreaIds.contains(orderReceiverCityId)) {
                    for (WapShippingQueryResultVO goodsList : goodsBaseList) {
                        Integer buyNum = goodsList.getGoodsNum();
                        // 包邮
                        if (shippingTransport.getFreePostageCond().intValue() <= buyNum.intValue()) {
                            // 设置商品运费为0
                            setGoodsShippingZero(goodsBaseList);
                        } else {

                            // 不满足包邮
                            // 根据商品数量设置商品运费
                            shippingFee = shippingFee.add(shippingTransport.getShippingPrice() == null ? new BigDecimal(0)
                                    : shippingTransport.getShippingPrice());
                            goodsList.setTotalGoodsShippingFee(shippingTransport.getShippingPrice() == null ? new BigDecimal(0)
                                    : shippingTransport.getShippingPrice());
                            shippingFee = setNoFeeByNum(shippingFee, num, shippingTransport, goodsBaseList);
                        }
                    }
                } else {
                    // 不包邮
                    Boolean flag = true;
                    List<WapShippingTransportResultVO> transportRules = this.baseMapper.selectShipping(shippingTransport.getId());

                    for (WapShippingTransportResultVO transportRule : transportRules) {

                        if (transportRule.getDefaultType().equals(1)) {
                            defaultTransportRule = transportRule;
                        }
                        List<Integer> areaIds = null;
                        if (!"0".equals(transportRule.getAreaIds()) && !"".equals(transportRule.getAreaIds())) {
                            areaIds = JsonUtils.StringToList2(transportRule.getAreaIds());
                        }

                        // 首重数量
                        BigDecimal defaultNum = transportRule.getDefaultNum();
                        BigDecimal defaultPrice = transportRule.getDefaultPrice();
                        BigDecimal addNum = transportRule.getAddNum();
                        BigDecimal addPrice = transportRule.getAddPrice();
                        if (null != areaIds) {
                            if (areaIds.contains(areaId)) {
                                flag = false;
                                // 获取运费
                                shippingFee = getIsFreePostageByNum2(shippingFee, num, shippingTransport, goodsBaseList,
                                        defaultNum, defaultPrice, addNum, addPrice);
                                break;
                            } else if (areaIds.contains(orderReceiverCityId)) {
                                flag = false;
                                // 获取运费
                                shippingFee = getIsFreePostageByNum2(shippingFee, num, shippingTransport, goodsBaseList,
                                        defaultNum, defaultPrice, addNum, addPrice);
                                break;
                            }
                        }
                    }
                    if (flag) {

                        if (defaultTransportRule != null) {
                            // 默认规则
                            BigDecimal defaultNum = defaultTransportRule.getDefaultNum();
                            BigDecimal defaultPrice = defaultTransportRule.getDefaultPrice();
                            BigDecimal addNum = defaultTransportRule.getAddNum();
                            BigDecimal addPrice = defaultTransportRule.getAddPrice();

                            // 获取运费
                            shippingFee = getIsFreePostageByNum2(shippingFee, num, shippingTransport, goodsBaseList,
                                    defaultNum, defaultPrice, addNum, addPrice);
                        } else {
                            setGoodsShippingZero(goodsBaseList);
                        }
                    }
                }
                // 按重量包邮
            } else {
                // 获取总重量
                if (freeAreaIds.contains(areaId)) {
                    shippingFee = getIsFreePostageByCubage2(shippingFee, grossCubage, shippingTransport, goodsBaseList,goodsBases);
                } else if (freeAreaIds.contains(orderReceiverCityId)) {
                    // 包邮
                    shippingFee = getIsFreePostageByCubage2(shippingFee, grossCubage, shippingTransport, goodsBaseList,goodsBases);
                } else {
                    // 不包邮
                    Boolean flag = true;
                    List<WapShippingTransportResultVO> transportRules = this.baseMapper.selectShipping(shippingTransport.getId());

                    for (WapShippingTransportResultVO transportRule : transportRules) {

                        if (transportRule.getDefaultType().equals(1)) {
                            defaultTransportRule = transportRule;
                        }

                        List<Integer> areaIds = null;
                        if (!"0".equals(transportRule.getAreaIds()) && !"".equals(transportRule.getAreaIds())) {
                            areaIds = JsonUtils.StringToList2(transportRule.getAreaIds());
                        }
                        // 首重重量
                        BigDecimal defaultNum = transportRule.getDefaultNum();
                        BigDecimal defaultPrice = transportRule.getDefaultPrice();
                        BigDecimal addNum = transportRule.getAddNum();
                        BigDecimal addPrice = transportRule.getAddPrice();
                        if (null != areaIds) {
                            if (areaIds.contains(areaId)) {
                                flag = false;

                                shippingFee = getIsFreePostageByCubage(shippingFee, grossCubage, goodsBaseList, defaultNum,
                                        defaultPrice, addNum, addPrice, goodsBases);
                                break;
                            } else if (areaIds.contains(orderReceiverCityId)) {
                                flag = false;
                                shippingFee = getIsFreePostageByCubage(shippingFee, grossCubage, goodsBaseList, defaultNum,
                                        defaultPrice, addNum, addPrice, goodsBases);
                                break;
                            }
                        }
                    }
                    if (flag) {

                        if (defaultTransportRule != null) {
                            // 默认规则
                            BigDecimal defaultNum = defaultTransportRule.getDefaultNum();
                            BigDecimal defaultPrice = defaultTransportRule.getDefaultPrice();
                            BigDecimal addNum = defaultTransportRule.getAddNum();
                            BigDecimal addPrice = defaultTransportRule.getAddPrice();

                            shippingFee = getIsFreePostageByCubage(shippingFee, grossCubage, goodsBaseList, defaultNum,
                                    defaultPrice, addNum, addPrice,goodsBases);
                        } else {
                            setGoodsShippingZero(goodsBaseList);
                        }
                    }
                }
            }
        } else {
            for (WapShippingQueryResultVO goodsBase : goodsBaseList) {

                goodsBase.setGoodsShippingFee(new BigDecimal(0));
            }
        }
        return shippingFee;
    }
    private BigDecimal getIsFreePostageByCubage(BigDecimal shippingFee, BigDecimal grossCubage,
                                                List<WapShippingQueryResultVO> goodsBaseList, BigDecimal defaultNum, BigDecimal defaultPrice,
                                                BigDecimal addNum, BigDecimal addPrice,List<GoodsInformationVO> goodsBases) {
        for (WapShippingQueryResultVO goodsBase : goodsBaseList) {
            BigDecimal goodsNum = new BigDecimal(0);
            for (GoodsInformationVO base : goodsBases) {
                if (goodsBase.getGoodsId().equals(base.getGoodsId())) {
                    goodsNum = BigDecimal.valueOf(base.getGoodsNum());
                }
            }
            BigDecimal allCubage = new BigDecimal(String.valueOf(goodsNum))
                    .multiply(goodsBase.getGoodsCubage() == null ? new BigDecimal(0) : goodsBase.getGoodsCubage());
            // 判断是否在首件内1 grossCubage
            if (defaultNum.compareTo(allCubage) >= 0) {
                shippingFee = shippingFee.add(defaultPrice);
                goodsBase.setTotalGoodsShippingFee(defaultPrice);
                goodsBase.setGoodsShippingFee(shippingFee.divide(goodsNum, 2, BigDecimal.ROUND_HALF_UP));
            } else {
                // 超过首件
                if (addNum.compareTo(new BigDecimal(0)) != 0 && addPrice.compareTo(new BigDecimal(0)) != 0) {
                    BigDecimal price = null;
                    // 超重的重量
                    double doubleValue = allCubage.subtract(defaultNum).doubleValue();
                    if ((new BigDecimal(doubleValue)).compareTo(addNum) < 1) {
                        price = addPrice.add(defaultPrice);
                    } else {
                        doubleValue = new BigDecimal(doubleValue).divide(addNum, BigDecimal.ROUND_HALF_UP).doubleValue();
                        price = new BigDecimal(Math.ceil(doubleValue)).multiply(addPrice).add(defaultPrice);
                    }
                    //商品邮费
                    shippingFee = shippingFee.add(price);
                    goodsBase.setTotalGoodsShippingFee(price);
                }
                setNoFeeByCubage(shippingFee, allCubage, goodsBaseList);
            }
        }
        return shippingFee;
    }
    private BigDecimal getIsFreePostageByCubage2(BigDecimal shippingFee, BigDecimal grossCubage,
                                                 WapShippingTransportResultVO shippingTransport, List<WapShippingQueryResultVO> goodsBaseList,
                                                 List<GoodsInformationVO> goodsBases ) {


        for (WapShippingQueryResultVO goodsBase : goodsBaseList) {
            BigDecimal goodsNum = new BigDecimal(0);
            for (GoodsInformationVO base : goodsBases) {
                if (goodsBase.getGoodsId().equals(base.getGoodsId())){
                    goodsNum = BigDecimal.valueOf(base.getGoodsNum());
                }
            }
            BigDecimal allCubage = new BigDecimal(String.valueOf(goodsNum))
                    .multiply(goodsBase.getGoodsCubage() == null ? new BigDecimal(0) : goodsBase.getGoodsCubage());
            // 包邮
            if (shippingTransport.getFreePostageCond() <= allCubage.intValue()) {
                setGoodsShippingZero2(goodsBase);
            } else {
                // 不满足包邮
                shippingFee = shippingFee.add(shippingTransport.getShippingPrice() == null ? new BigDecimal(0)
                        : shippingTransport.getShippingPrice());
                goodsBase.setTotalGoodsShippingFee(shippingTransport.getShippingPrice() == null ? new BigDecimal(0)
                        : shippingTransport.getShippingPrice());
                setNoFeeByCubage(shippingFee, allCubage, goodsBaseList);
            }
        }
        return shippingFee;
    }
    private void setNoFeeByCubage(BigDecimal shippingFee, BigDecimal grossCubage,
                                  List<WapShippingQueryResultVO> goodsBaseList) {

        BigDecimal otherGoodsShippingFee = new BigDecimal(0);
        for (int i = 0; i < goodsBaseList.size(); i++) {
            WapShippingQueryResultVO goodsBase = goodsBaseList.get(i);

            if (i == goodsBaseList.size() - 1) {
                BigDecimal goodsShippingFee = shippingFee.subtract(otherGoodsShippingFee);
                goodsBase.setGoodsShippingFee(goodsShippingFee);
            } else {
                if (goodsBase.getGoodsCubage().compareTo(new BigDecimal(0)) == 0) {
                    goodsBase.setGoodsShippingFee(new BigDecimal(0));
                } else {
                    BigDecimal goodsCubage = goodsBase.getGoodsCubage().divide(grossCubage, 2, BigDecimal.ROUND_DOWN);
                    BigDecimal goodsShippingFee = shippingFee.multiply(goodsCubage).setScale(2, BigDecimal.ROUND_DOWN);
                    goodsBase.setGoodsShippingFee(goodsShippingFee);
                    otherGoodsShippingFee = otherGoodsShippingFee.add(goodsShippingFee);
                }

            }
        }
    }
    private void setGoodsShippingZero2(WapShippingQueryResultVO goodsBase) {
        goodsBase.setGoodsShippingFee(new BigDecimal(0));
    }
    private BigDecimal getIsFreePostageByNum2(BigDecimal shippingFee, Integer num,
                                              WapShippingTransportResultVO shippingTransport, List<WapShippingQueryResultVO> goodsBaseList,
                                              BigDecimal defaultNum, BigDecimal defaultPrice, BigDecimal addNum, BigDecimal addPrice) {
        for (WapShippingQueryResultVO goodsList : goodsBaseList) {
            Integer buyNum = goodsList.getGoodsNum();
            // 判断是否在首件内
            if (buyNum.intValue() <= defaultNum.intValue()) {
                shippingFee = shippingFee.add(defaultPrice);
                // 根据商品数量设置商品运费
                goodsList.setTotalGoodsShippingFee(defaultPrice);
                shippingFee = setNoFeeByNum(shippingFee, buyNum, shippingTransport, goodsBaseList);
            } else {
                // 超过首件
                if (addNum.compareTo(new BigDecimal(0)) != 0 && addPrice.compareTo(new BigDecimal(0)) != 0) {
                    BigDecimal subNum = new BigDecimal(buyNum).subtract(defaultNum);
                    BigDecimal[] bigDecimals = subNum.divideAndRemainder(addNum);
                    System.out.println(bigDecimals[0]);//商
                    System.out.println(bigDecimals[1]);//余数
                    //当余数不为0是 商加1 否则不加
                    if(bigDecimals[1].compareTo(new BigDecimal(0)) != 0){
                        shippingFee = shippingFee.add((bigDecimals[0].add(new BigDecimal(1))) .multiply(addPrice).add(defaultPrice));
                        goodsList.setTotalGoodsShippingFee((bigDecimals[0].add(new BigDecimal(1))) .multiply(addPrice).add(defaultPrice));
                    }else{
                        shippingFee = shippingFee.add(bigDecimals[0] .multiply(addPrice).add(defaultPrice));
                        goodsList.setTotalGoodsShippingFee(bigDecimals[0] .multiply(addPrice).add(defaultPrice));
                    }
                }
                // 因为超过首件的运费为0 所以就不管当前商品有多少件商品都按 首件运费计算
                if(addPrice.compareTo(new BigDecimal(0)) == 0){
                    shippingFee = shippingFee.add(defaultPrice);
                    goodsList.setTotalGoodsShippingFee(defaultPrice);
                }
                // 根据商品数量设置商品运费

                shippingFee = setNoFeeByNum(shippingFee, num, shippingTransport, goodsBaseList);

            }
        }
        return shippingFee;
    }
    private BigDecimal setNoFeeByNum(BigDecimal shippingFee, Integer num, WapShippingTransportResultVO shippingTransport,
                                     List<WapShippingQueryResultVO> goodsBaseList) {
        BigDecimal otherGoodsShippingFee = new BigDecimal(0);
        for (int i = 0; i < goodsBaseList.size(); i++) {
            WapShippingQueryResultVO goodsBase = goodsBaseList.get(i);

            if (i == goodsBaseList.size() - 1) {
                BigDecimal goodsShippingFee = shippingFee.subtract(otherGoodsShippingFee);
                goodsBase.setGoodsShippingFee(goodsShippingFee);
            } else {
                BigDecimal goodsNum = new BigDecimal(goodsBase.getGoodsNum()).divide(new BigDecimal(num), 2,
                        BigDecimal.ROUND_DOWN);
                BigDecimal goodsShippingFee = shippingFee.multiply(goodsNum).setScale(2, BigDecimal.ROUND_DOWN);
                otherGoodsShippingFee = otherGoodsShippingFee.add(goodsShippingFee);
                goodsBase.setGoodsShippingFee(goodsShippingFee);
            }
        }

        return shippingFee;
    }
    private void setGoodsShippingZero(List<WapShippingQueryResultVO> goodsBaseList) {
        for (WapShippingQueryResultVO goodsBase : goodsBaseList) {
            goodsBase.setGoodsShippingFee(new BigDecimal(0));
        }
    }
    private ActivityGoodsDetailDTO dealActivity(Integer goodsId, Integer goodsMaxSale, Integer commonId, Integer commonIsXian) {
        // 活动商品详情
        ActivityGoodsDetailDTO activityGoodsDetail = null;
        // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
        if (!commonIsXian.equals(0)) {
            activityGoodsDetail = new ActivityGoodsDetailDTO();
            if (commonIsXian.equals(2)) {
                // 秒杀
                AppSeckillGoodsQueryResultVO seckillGoods = activityServiceClient.selectSeckillByGoodsId2(goodsId);
                commonIsXian = dealSeckillActivity(goodsId, goodsMaxSale, commonIsXian, activityGoodsDetail);
                if(seckillGoods != null) {
                    activityGoodsDetail.setGoodsUpperLimit(seckillGoods.getGoodsUpperLimit());
                    activityGoodsDetail.setSeckillGoods(seckillGoods);
                }
            } else if (commonIsXian.equals(3)) {
                // 限时折扣
                AppDiscountGoodsQueryResultVO discountGoods = activityServiceClient.selectDiscountByGoodsId(goodsId);
                commonIsXian = dealDiscountActivity(goodsId, goodsMaxSale, commonIsXian, activityGoodsDetail);
                if(discountGoods != null) {
                    activityGoodsDetail.setGoodsUpperLimit(discountGoods.getGoodsUpperLimit());
                    activityGoodsDetail.setDiscountGoods(discountGoods);
                }
            } else if (commonIsXian.equals(4)) {
                // 拼团
                commonIsXian = dealPintuanActivity(commonId, commonIsXian, goodsId, activityGoodsDetail);
            } else if (commonIsXian.equals(5)) {
                // 满减赠折
                commonIsXian = dealManjianzengzheActivity(commonId, goodsMaxSale, commonIsXian, goodsId, activityGoodsDetail);
            }else {
                commonIsXian = 0;
            }

            activityGoodsDetail.setActivityStatus(commonIsXian);
        }

        return activityGoodsDetail;
    }

    private Integer dealManjianzengzheActivity(Integer commonId, Integer goodsMaxSale, Integer commonIsXian, Integer goodsId, ActivityGoodsDetailDTO activityGoodsDetail) {
        ManjianzengzheGoodsQueryResultVO manjianzengzheGoods = activityServiceClient.selectReductionPolicyByGoodsId(commonId);
        if (null != manjianzengzheGoods && null!=manjianzengzheGoods.getPromotionId()) {
            if (DateUtils.compareDate2(manjianzengzheGoods.getEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), manjianzengzheGoods.getEndTime());
                activityGoodsDetail.setOverplusTime(overplusTime);
                List<ManjianzengzheGoodsRuleQueryDTO> ruleList = activityServiceClient.selectReductionPolicyRuleDetailList(manjianzengzheGoods.getPromotionId());
                activityGoodsDetail.setPromotionId(manjianzengzheGoods.getPromotionId());
                activityGoodsDetail.setRuleList(ruleList);
                activityGoodsDetail.setMjzzPrice(manjianzengzheGoods.getGoodsPrice());
                activityGoodsDetail.setGoodsLowerLimit(0);
                activityGoodsDetail.setGoodsUpperLimit(goodsMaxSale);
                activityGoodsDetail.setGoodsId(manjianzengzheGoods.getGoodsId());

            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }

        return commonIsXian;
    }

    private Integer dealPintuanActivity(Integer commonId, Integer commonIsXian, Integer goodsId, ActivityGoodsDetailDTO activityGoodsDetail) {
        AppPintuanGoodsQueryResultVO pintuanGoods = activityServiceClient.selectpiecingTogetherByGoodsId(commonId, goodsId);
        if (null != pintuanGoods) {
            if (DateUtils.compareDate2(pintuanGoods.getEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), pintuanGoods.getEndTime());
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setPintuanPrice(pintuanGoods.getPrice());
                activityGoodsDetail.setPriceOne(pintuanGoods.getPriceOne());
                activityGoodsDetail.setActivityPrice(pintuanGoods.getPrice());
            } else {
                commonIsXian = 0;
            }
            pintuanGoods.setCommonIsXian(commonIsXian);
        } else {
            commonIsXian = 0;
        }

        return commonIsXian;
    }

    private Integer dealDiscountActivity(Integer goodsId, Integer goodsMaxSale, Integer commonIsXian, ActivityGoodsDetailDTO activityGoodsDetail) {
        AppDiscountGoodsQueryResultVO discountGoods = activityServiceClient.selectDiscountByGoodsId(goodsId);
        Long overplusTime = null;
        if (null != discountGoods) {
            Integer discountState = discountGoods.getDiscountGoodsState();
            if (DateUtils.compareDate2(discountGoods.getGoodsEndTime())) {
                activityGoodsDetail.setActivityEndTime(discountGoods.getGoodsEndTime());
                activityGoodsDetail.setActivityStartStatus(discountState);
                activityGoodsDetail.setDiscountAmount(discountGoods.getDiscountAmount());
                activityGoodsDetail.setDiscountTitle(discountGoods.getDiscountTitle());
                activityGoodsDetail.setActivityStartTime(discountGoods.getGoodsStartTime());
                //活动已经开始
                if (null != discountState && 1 == discountState) {
                    overplusTime = DateUtils.getSecondByMinusDate(new Date(), discountGoods.getGoodsEndTime());
                }//活动正在预热
                else if (null != discountState && 4 == discountState) {
                    overplusTime = DateUtils.getSecondByMinusDate(new Date(), discountGoods.getGoodsStartTime());
                }

                // 设限
                if (!discountGoods.getGoodsLowerLimit().equals(0)) {
                    activityGoodsDetail.setGoodsLowerLimit(discountGoods.getGoodsLowerLimit());
                } else {
                    activityGoodsDetail.setGoodsLowerLimit(0);
                }
                if (!discountGoods.getDiscountUpperTime().equals(0)) {
                    activityGoodsDetail.setDiscountUpperTime(discountGoods.getDiscountUpperTime());
                } else {
                    activityGoodsDetail.setDiscountUpperTime(0);
                }
                // 设限
                if (!discountGoods.getGoodsUpperLimit().equals(0)) {
                    activityGoodsDetail.setGoodsUpperLimit(discountGoods.getGoodsUpperLimit());
                } else {
                    activityGoodsDetail.setGoodsUpperLimit(0);
                }
                activityGoodsDetail.setGoodsBuyCount(
                        discountGoods.getGoodsBuyCount() != null ? discountGoods.getGoodsBuyCount() : 0);
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setActivityPrice(discountGoods.getDiscountPrice());
            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }
        return commonIsXian;
    }

    private Integer dealSeckillActivity(Integer goodsId, Integer goodsMaxSale, Integer commonIsXian, ActivityGoodsDetailDTO activityGoodsDetail) {
        AppSeckillGoodsQueryResultVO seckillGoods = activityServiceClient.selectSeckillByGoodsId2(goodsId);
        if (null != seckillGoods) {
            if (DateUtils.compareDate2(seckillGoods.getGoodsEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), seckillGoods.getGoodsEndTime());
                activityGoodsDetail.setActivityEndTime(seckillGoods.getGoodsEndTime());
                // 判断是否开始
                if (DateUtils.compareDate2(seckillGoods.getGoodsStartTime())) {
                    activityGoodsDetail.setActivityStartStatus(0);
                    overplusTime = DateUtils.getSecondByMinusDate(new Date(), seckillGoods.getGoodsStartTime());
                } else {
                    activityGoodsDetail.setActivityStartStatus(1);
                }
                // 设限
                if (!seckillGoods.getGoodsLowerLimit().equals(0)) {
                    activityGoodsDetail.setGoodsLowerLimit(seckillGoods.getGoodsLowerLimit());
                } else {
                    activityGoodsDetail.setGoodsLowerLimit(0);
                }
                // 设限
                if (!seckillGoods.getGoodsUpperLimit().equals(0)) {
                    activityGoodsDetail.setGoodsUpperLimit(seckillGoods.getGoodsUpperLimit());
                } else {
                    activityGoodsDetail.setGoodsUpperLimit(goodsMaxSale);
                }
                activityGoodsDetail
                        .setGoodsBuyCount(seckillGoods.getSeckillNum() != null ? seckillGoods.getSeckillNum() : 0);
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setActivityPrice(seckillGoods.getSeckillPrice());

                activityGoodsDetail.setCommonStock(seckillGoods.getSeckillNums() != null ? seckillGoods.getSeckillNums() : 0);
                activityGoodsDetail.setDiscountTitle(seckillGoods.getSeckillTitle());
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setActivityPrice(seckillGoods.getSeckillPrice());
                activityGoodsDetail.setActivityStartTime(seckillGoods.getGoodsStartTime());

            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }
        return commonIsXian;
    }

    @Override
    public ResponseResult getGoodsDetails(Integer goodsId) {
        ReceiveGoodsDetailsVO detail = this.baseMapper.selectCartMessage(goodsId);
        if(null == detail){
            return ResponseResult.fail(BizCodeEnume.PRODUCT_HAS_BEEN_REMOVED_FROM_THE_SHELF.getCode(),BizCodeEnume.PRODUCT_HAS_BEEN_REMOVED_FROM_THE_SHELF.getMsg());
        }
        detail.setGoodsSpecChineseValue(detail.getGoodsSpecChineseValue());

        if (!detail.getCommonState().equals(1) || !detail.getCommonVerify().equals(1)
//                || !detail.getCartStatus().equals(1)
               ) {
            detail.setGoodsStock(0);
            detail.setCartStatus(0);
        }

        // 不限购
        if (detail.getCommonLimit().equals(0) || detail.getGoodsMaxSale().equals(0)) {
            detail.setGoodsMaxSale(0);
        }
        // 活动
        Integer integer = dealActivityState(detail.getGoodsId(), detail.getGoodsMaxSale(),
                detail.getCommonId(), detail.getCommonIsXian());
        if (integer != null && integer == -100){
            return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
        }
        detail.setActivityGoodsState(integer);
        ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(detail.getGoodsId(), detail.getGoodsMaxSale(),
                detail.getCommonId(), detail.getCommonIsXian());

        if (null != activityGoodsDetail && !activityGoodsDetail.getActivityStatus().equals(0)) {
            detail.setActivityStatus(activityGoodsDetail.getActivityStatus());
            detail.setActivityGoodsDetail(activityGoodsDetail);
            detail.setCommonIsXian(activityGoodsDetail.getActivityStatus());
            if (!activityGoodsDetail.getActivityStatus().equals(4)) {
                detail.setGoodsMaxSale(activityGoodsDetail.getGoodsUpperLimit());
                detail.setGoodsMinSale(activityGoodsDetail.getGoodsLowerLimit());
            }
        } else {
            detail.setActivityStatus(0);
            detail.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
            detail.setCommonIsXian(0);
        }

        if (detail.getGoodsMaxSale().equals(0)) {
            detail.setGoodsMaxSale(0);
        }

        return ResponseResult.success(JsonUtils.toString(detail));
    }

    private Integer dealActivityState(Integer goodsId, Integer goodsMaxSale, Integer commonId,
                                      Integer commonIsXian) {
        // 活动商品详情
        ActivityGoodsDetailDTO activityGoodsDetail = null;
        Integer activityGoodsState = null;
        // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
        if (!commonIsXian.equals(0)) {
            activityGoodsDetail = new ActivityGoodsDetailDTO();
            if (commonIsXian.equals(2)) {
                // 秒杀
                AppSeckillGoodsQueryResultVO seckillGoods = activityServiceClient.selectSeckillByGoodsId2(goodsId);
                if (seckillGoods == null){
                    return -100;
                }
                activityGoodsState = seckillGoods.getSeckillGoodsState();
            } else if (commonIsXian.equals(3)) {
                // 限时折扣
                AppDiscountGoodsQueryResultVO discountGoods = activityServiceClient.selectDiscountByGoodsId(goodsId);
                if (discountGoods == null){
                    return -100;
                }
                activityGoodsState = discountGoods.getDiscountGoodsState();
            }
            activityGoodsDetail.setActivityStatus(commonIsXian);
        }

        return activityGoodsState;
    }



    @Override
    public ResponseResult queryTransportTemplateList(UserTokenBeanDTO param) {
        List<TransportTemplateListVO> results = new ArrayList<TransportTemplateListVO>();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_TRANSPORT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            results = shopTransportTemplateMapper.selectByShopId2(Integer.valueOf(userPermissionsResult.getShopId()));

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success(results);
    }


    @Override
    @Transactional
    public ResponseResult deleteTransportTemplate(ManageTransportTemplateDTO param) {

        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_TRANSPORT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            // 删除运费模板
            shopTransportTemplateMapper.deleteByPrimaryKey(param.getTemplateId());
            shopTransportRuleMapper.deleteByTemplateId(param.getTemplateId());
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    @Transactional
    public ResponseResult updateTransportTemplate(GdbMerchantTransportTemplateDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_TRANSPORT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            // 已有的店铺id
            List<Integer> transportTemplateIdList = Lists.newArrayList();

            param.setShopId(Integer.valueOf(userPermissionsResult.getShopId()));
            // param.setShopId(158495);
            if (param.getIsFreePostage() == 0) {
                param.setFreePostageAreas("");
            }
            // 更新或新增运费模板
            if (null != param.getId()) {
                // 更新模板
                shopTransportTemplateMapper.updateByPrimaryKeySelective(param);
                // 获取不包邮区域
                List<GdbMerchantTransportRuleDTO> transportRules = param.getTransportRules();
                // 添加不包邮区域
                if (!CollectionUtils.isEmpty(transportRules)) {
                    Integer transportTemplateId = param.getId();
                    // 定义集合
                    List<GdbMerchantTransportRuleDTO> addTransportRule = new ArrayList<GdbMerchantTransportRuleDTO>();
                    List<GdbMerchantTransportRuleDTO> updateTransportRule = new ArrayList<GdbMerchantTransportRuleDTO>();

                    for (GdbMerchantTransportRuleDTO transportRule : transportRules) {
                        // 初始化参数
                        if(transportRule.getAddNum().equals(new BigDecimal(0))  ){
                            transportRule.setAddNum(new BigDecimal(1));
                        }
                        transportRule.setTransportTemplateId(transportTemplateId);
                        transportRule.setRuleType(param.getRuleType());
                        transportRule.setUpdateTime(new Date());

                        if (transportRule.getLogisticsType() == null) {
                            transportRule.setLogisticsType("1");
                        }

                        if (null == transportRule.getDefaultNum()) {
                            transportRule.setDefaultNum(new BigDecimal(0));
                        }

                        if (null == transportRule.getDefaultPrice()) {
                            transportRule.setDefaultPrice(new BigDecimal(0));
                        }

                        if (transportRule.getId() == null) {

                            addTransportRule.add(transportRule);
                        } else {
                            transportTemplateIdList.add(transportRule.getId().intValue());
                            updateTransportRule.add(transportRule);
                        }
                        if (transportRule.getAreaIds() == null) {
                            transportRule.setAreaIds("0");
                        }
                    }

                    if (!CollectionUtils.isEmpty(updateTransportRule)) {
                        shopTransportRuleMapper.updateBatch(updateTransportRule);
                        shopTransportRuleMapper.deleteByTemplateIdList(transportTemplateIdList, transportTemplateId);
                    }

                    if (!CollectionUtils.isEmpty(addTransportRule)) {
                        shopTransportRuleMapper.insertBatch(addTransportRule);
                    }

                }
            } else {
                //添加包邮区域内运费规则
                shopTransportTemplateMapper.insertSelective(param);

                List<GdbMerchantTransportRuleDTO> transportRules = param.getTransportRules();
                // 添加不包邮区域
                if (!CollectionUtils.isEmpty(transportRules)) {
                    Integer transportTemplateId = param.getId();
                    //遍历规则
                    for (GdbMerchantTransportRuleDTO transportRule : transportRules) {
                        //获取添加数量 （重量 或 件数）
                        if(transportRule.getAddNum().equals(new BigDecimal(0))  ){
                            transportRule.setAddNum(new BigDecimal(1));
                        }
                        transportRule.setTransportTemplateId(transportTemplateId);
                        //规则类型,1重量2件数
                        transportRule.setRuleType(param.getRuleType());
                        transportRule.setUpdateTime(new Date());
                        if (transportRule.getLogisticsType() == null) {
                            transportRule.setLogisticsType("1");
                        }
                        //区域城市id
                        if (transportRule.getAreaIds() == null) {
                            transportRule.setAreaIds("0");
                        }
                        transportRule.setDefaultNum(null == transportRule.getDefaultNum() ?
                                BigDecimal.ZERO : transportRule.getDefaultNum());
                    }
                    //添加不包邮 区域的运费规则
                    shopTransportRuleMapper.insertBatch(transportRules);
                }

            }
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();

    }



    @Override
    public ResponseResult queryTransportTemplateDetail(ManageTransportTemplateDTO param) {

        GdbMerchantTransportTemplateVO transportTemplate = new GdbMerchantTransportTemplateVO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_TRANSPORT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            transportTemplate = shopTransportTemplateMapper.selectByPrimaryKey(param.getTemplateId());

            if (null != transportTemplate) {

                String freePostageAreas = transportTemplate.getFreePostageAreas();
                if (freePostageAreas != null && !freePostageAreas.equals("")) {
                    List<Integer> stringToList2 = JsonUtils.StringToList2(freePostageAreas);
                    transportTemplate.setFreePostageAreas(JSON.toJSONString(stringToList2));
                }

            }
            List<GdbMerchantTransportRuleDTO> transportRules = shopTransportRuleMapper
                    .selectByTemplateId(param.getTemplateId());
            if (!CollectionUtils.isEmpty(transportRules)){
                transportTemplate.setTransportRules(transportRules);
            }

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success(transportTemplate);
    }

    @Override
    public ResponseResult queryShippingQuery(ShippingQueryListDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            // 结果集
            // 运费
            BigDecimal shippingFee = new BigDecimal(0);
            // 商品价格
            BigDecimal goodsPrice = new BigDecimal(0);
            Integer num = param.getGoodsNum();
            Integer areaId = param.getOrderReceiverAreaId();
            Integer orderReceiverCityId = param.getOrderReceiverCityId();
            Integer orderReceiverProvinceId = param.getOrderReceiverProvinceId();
            // 获取商品重量和运费模板id
            ShippingInfoDTO goodsBase = this.baseMapper.selectShippingInfo(param.getGoodsId());
            Integer shopId = goodsBase.getShopId();
            // 查询店铺免运费额度
            BigInteger shopFreeShipping = shopBaseMapper.selectOne(new LambdaQueryWrapper<ShopBaseEntity>()
                                       .eq(ShopBaseEntity::getShopId,shopId)).getShopFreeShipping();

            // 获取商品价格
            goodsPrice = goodsBase.getGoodsPrice().multiply(new BigDecimal(num)).add(goodsPrice);
            // 查询运费规则
            if (goodsBase.getTransportTemplate() == 0) {
                shippingFee = shippingFee.add(new BigDecimal(0));
                return ResponseResult.success(shippingFee);
            }
            ShopTransportTemplateEntity shippingTransport = this.baseMapper.selectById(goodsBase.getTransportTemplate());

            // 判断是否包邮
            if (null == shippingTransport) {
                return ResponseResult.success(0);
            }
            shippingFee = getShipping(shippingFee, areaId, orderReceiverCityId, num, orderReceiverProvinceId, goodsBase,
                    shippingTransport);

            if (null != shopFreeShipping) {
                if (goodsPrice.compareTo(new BigDecimal(shopFreeShipping)) > 1
                        || goodsPrice.compareTo(new BigDecimal(shopFreeShipping)) == 0) {
                    shippingFee = new BigDecimal(0);
                }
            }
            return ResponseResult.success(shippingFee);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult selectTemplateById(Integer transportTemplate) {
        ShopTransportTemplateEntity shippingTransport = this.baseMapper.selectById(transportTemplate);
        return ResponseResult.success(shippingTransport);
    }

    @Override
    public List<TransportTemplateVO> selectByShopId(Integer shopId) {
        return this.baseMapper.selectByShopId(shopId);
    }
}
